package com.gitee.sidihuo.sse.base;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.nio.charset.StandardCharsets;

/**
 *  流式响应Http接口SSE对象utf-8指定编码
 */
@Slf4j
public class SseEmitterUtf8 extends SseEmitter {

    private long createTime = System.currentTimeMillis();

    /**
     * utf-8
     *
     * @param timeout 超时时间 毫秒  （超过这个时间和客户端中断http连接） 0L就是不超时
     */
    public SseEmitterUtf8(Long timeout) {
        super(timeout);
        if (timeout == 0L) {
            log.info("SseEmitterUtf8 set timeout is forever , but I suggest you set large values other than 0L");
        }
    }

    /**
     * utf-8  默认超时时间1分钟
     */
    public SseEmitterUtf8() {
        super(60000L);
    }

    @Override
    protected void extendResponse(ServerHttpResponse outputMessage) {
        super.extendResponse(outputMessage);
        HttpHeaders headers = outputMessage.getHeaders();
        headers.setContentType(new MediaType(MediaType.TEXT_EVENT_STREAM, StandardCharsets.UTF_8));
    }

    public long getCreateTime() {
        return createTime;
    }

}
